package br.ufpe.cin.msc.jrsj2.recommender.message;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import br.ufpe.cin.msc.jrsj2.recommender.util.ClientHash;

public abstract class ClientQuit {

	private static class MessageHandler extends DefaultHandler {
		private String clientId;

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (qName.equals("client-quit")) {
				if (attributes.getLength() == 1) {
					clientId = attributes.getValue("id");
				}
			}
		}
	}

	public static String getClientId(String message)
			throws ParserConfigurationException, SAXException, IOException {
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		InputSource is = new InputSource(new StringReader(message));
		MessageHandler handler = new MessageHandler();
		parser.parse(is, handler);

		return ClientHash.getClientHashString(handler.clientId);
	}
}
